package com.simp.utils;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;
import java.util.Set;

/**
 * @author pan.shun
 * @since 2022/3/1 15:50
 */
@Slf4j
public class IPUtils {

    private static final Logger log = LoggerFactory.getLogger(IPUtils.class);
    public static final Set<String> IP_HEADER_SET = Sets.newHashSet(new String[]{"browser-ip", "X-Real-IP", "browser", "X-Forwarded-For", "Proxy-Client-IP", "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR"});

    public IPUtils() {
    }

    public static String getIp(HttpServletRequest request) {
        String ip = null;
        JSONObject ipObj = new JSONObject();

        try {
            Iterator var3 = IP_HEADER_SET.iterator();

            while(var3.hasNext()) {
                String name = (String)var3.next();
                ip = request.getHeader(name);
                if (org.apache.commons.lang3.StringUtils.isNotBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
                    ipObj.put(name, ip);
                }
            }

            ip = request.getRemoteAddr();
            if (org.apache.commons.lang3.StringUtils.isNotBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
                ipObj.put("RemoteAddr", ip);
            }

            ip = request.getRemoteHost();
            if (org.apache.commons.lang3.StringUtils.isNotBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
                ipObj.put("RemoteHost", ip);
            }
        } catch (Exception var5) {
            log.error("获取IP失败：{}", var5.getMessage());
        }

        return ipObj.toJSONString();
    }
}
